package com.example.vod.controller;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.ram.model.v20150501.DeleteRoleRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.example.handler.GuliException;
import com.example.utils.R;
import com.example.vod.service.VodService;
import com.example.vod.utils.ConstantVodUtils;
import com.example.vod.utils.InitVodClient;
import com.sun.org.glassfish.gmbal.ParameterNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

//@CrossOrigin  //跨域
@RestController
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;
    //上传视频到阿里云
    @PostMapping("/uploadAlyVideo")
    public R  uploadAlyVideo(MultipartFile file){

        String vid=vodService.uploadAlyVideo(file);

        return  R.ok().data("vid",vid);
    }
    //根据视频id删除视频
    @DeleteMapping("/removeAlyVideo/{id}")
    public  R  deleteAlyVideo(@PathVariable String id){
        try{
          //初始化
            DefaultAcsClient client= InitVodClient.initVodClient(ConstantVodUtils.ACESS_KEY_ID,ConstantVodUtils.ACESS_KEY_SECRET);
            //request
            DeleteVideoRequest request=new DeleteVideoRequest();
            request.setVideoIds(id);
            //调用初始化方法删除视频
            client.getAcsResponse(request);
            return  R.ok();


        }catch (Exception e){
                e.printStackTrace();
                throw  new GuliException(20001,"删除单个视频失败");
        }
    }

    //删除多个视频
    @DeleteMapping("/deleteBatch")
    public  R deleteBatchVideo(@RequestParam("videoIdList") List<String> videoIdList){

        vodService.removeVideoList(videoIdList);


        return  R.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("/getPlayAuth/{id}")
    public  R  getPlayAuth(@PathVariable String id){
        //创建初始化对象
        try {
            DefaultAcsClient client=
                    InitVodClient.initVodClient(ConstantVodUtils.ACESS_KEY_ID,ConstantVodUtils.ACESS_KEY_SECRET);

                //创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request=new GetVideoPlayAuthRequest();
            //想request中设置视频id
             request.setVideoId(id);
             //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return  R.ok().data("playAuth",playAuth);
        } catch (ClientException e) {
            e.printStackTrace();
            throw  new GuliException(20001,"获取凭证失败");
        }
    }

}
